#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# s = input('请输入年龄:')
# age = int(s)
# if age >= 18:
#     print('adult')
#     print('成人')
# else:
#     print =('teenager')
#     print =('少年')

# s = input('birth: ')
# birth = int(s)
# if birth < 2000:
#     print('00前')
# else:
#     print('00后')

# s1 = 72
# s2 = 85
# r = (s2-s1)/100
# print('成绩提升的百分点 %.2f' % r)

# names = ['AA', 'bb', 'cc']
# for name in names:
#     print(name)

# sum = 0

# from math import sqrt
# abs


# -*- coding: utf-8 -*-
# def findMinAndMax(L):
#     min = L and L[0] or None;
#     max = L and L[0] or None;
#     for x in L :
#         min = min > x and x or min;
#         max = max < x and x or max;
#     return (min, max);

# if findMinAndMax([]) != (None, None):
#     print('测试失败!')
# elif findMinAndMax([7]) != (7, 7):
#     print('测试失败!')
# elif findMinAndMax([7, 1]) != (1, 7):
#     print('测试失败!')
# elif findMinAndMax([7, 1, 3, 9, 5]) != (1, 9):
#     print('测试失败!')
# else:
#     print('测试成功!')
    
# def fib(max):
#     n, a, b = 0, 0 ,1
#     while n < max:
#         print(b)
#         a, b = b, a+b
#         n = n+1
#     return 'done'

# fib(6)

# def fib(max):
#     n, a, b = 0, 0 ,1
#     while n < max:
#         yield b
#         a, b = b, a+b
#         n = n+1
#     return 'done'

# for n in fib(6):
#     print(n)

# g = fib(6)
# while True:
#     try:
#         x = next(g)
#         print(x)
#     except StopIteration as e:
#         print(e.value)
#         break

# a = (1,2,3)

# def aa(cc, bb):
#     print(cc, bb)
#     pass

# aa(1, 2)

# class Student(object):

#     def __init__(self, name, score):
#         self.__name = name
#         self.__score = score

#     def get_name(self):
#         return self.__name

#     def get_score(self):
#         return self.__score

#     def set_score(self, score):
#         if 0 <= score <= 100:
#             self.__score = score
#         else:
#             raise ValueError('bad score')

#     def get_grade(self):
#         if self.__score >= 90:
#             return 'A'
#         elif self.__score >= 60:
#             return 'B'
#         else:
#             return 'C'

# bart = Student('Bart Simpson', 59)
# print('bart.get_name() =', bart.get_name())
# bart.set_score(60)
# print('bart.get_score() =', bart.get_score())

# print('DO NOT use bart._Student__name:', bart._Student__name)

# def foo(s):
#     aa = """
#     ddd
#     """
#     pass

# print('End')

# class FooError(ValueError):
#     pass

# def foo(s):
#     n = int(s)
#     if n==0:
#         raise FooError('invalid value: %s' % s)
#     return 10 / n

# foo('0')
# print('End')

# $ python err.py
# >>> n = 0
# Traceback (most recent call last):
#   ...
# ZeroDivisionError: integer division or modulo by zero

# $ python err.py
# INFO:root:n = 0
# Traceback (most recent call last):
#   File "err.py", line 8, in <module>
#     print(10 / n)
# ZeroDivisionError: division by zero

# import os
# print(os.name)
# # print(os.environ)
# print(os.environ['PATH'])
# print(os.path.abspath('.'))
# a = [x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1]=='.py']
# print(a)

# from multiprocessing import Process
# import os, time, random

# def run_proc(name):
#   """
#   docstring
#   """
#   print('Run child process %s (%s)...' % (name, os.getpid()))

# if __name__ == '__main__':
#   print('Parent process%s.' % os.getpid())  
#   p = Process(target=run_proc, args=('test',))
#   print('Child process will start.')
#   p.start()
#   p.join()
#   print('Child process end.')

# print(__name__)

# import re

# a = re.match(r'^\d{3}\-\d{3,8}$', '010 12345')
# print(a)

# a = 'a b   c'.split(' ')
# print(a)

# a = re.split(r'\s+', 'a b   c')
# print(a)

# 下一节
# from datetime import datetime
# now = datetime.now()
# print(now)

# print(type(now))

# dt= datetime(2015, 4, 19, 12, 20)
# print(dt)
# print(dt.timestamp()) # unit second

# # timestamp = 0 = 1970-1-1 08:00:00 UTC+8:00

# t = 1429417200.0
# print(datetime.fromtimestamp(t))
# print(datetime.utcfromtimestamp(t))

# cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S')
# print(cday)

# 下一节
# from collections import namedtuple
# Point = namedtuple('Point', ['x', 'y'])
# p = Point(1,2)
# print(p.x)
# print(p.y)
# a = isinstance(p, Point)
# print(a)
# a = isinstance(p, tuple)
# print(a)

# from collections import deque
# q = deque(['a','b','c'])
# q.append('x')
# print(q)
# q.appendleft('y')
# print(q)
# q.pop()
# print(q)
# q.popleft()
# print(q)

# from collections import defaultdict
# dd = defaultdict(lambda : 'N/A')
# dd['key1'] = 'abc'
# print(dd['key1'])
# print(dd['key2'])

# from collections import OrderedDict
# # d = dict([('a', 1), ('b',2), ('c',3)])
# d = {'a':1, 'b':2, 'c':3}
# print(d)
# od = OrderedDict([('a', 1), ('b',2), ('c',3)])
# print(od)
# od = OrderedDict()
# od['z'] = 1
# od['x'] = 2
# od['y'] = 3
# print(od)
# print(od.keys())
# print(type(od.keys()))
# k = list(od.keys())
# print(k)

# ChainMap
# Counter

# 下一节
# import hashlib
# md5 = hashlib.md5()
# md5.update('aaa'.encode('UTF-8'))
# print(md5.hexdigest())

# import hmac
# def hmac_md5(key, s):
#     return hmac.new(key.encode('utf-8'), s.encode('utf-8'), 'MD5').hexdigest()
# print(hmac_md5('a', 'aa'))

# 下一节
# import itertools
# # natuals = itertools.count(1)
# # for n in natuals:
# #     print(n)

# cs = itertools.cycle('ABC')
# for c in cs:
#     print(c)

# 下一节
# from urllib import request

# with request.urlopen('https://www.qq.com') as f:
#     data = f.read()
#     print('Status:', f.status, f.reason)
#     for k,v in f.getheaders():
#         print('%s:%s' % (k,v))
#     print('Data:', data.decode('UTF-8'))

# 下一节
# from PIL import Image
# im = Image.open('./OIP.jpg')
# w, h = im.size
# print('Original image size: %sx%s' % (w,h))
# im.thumbnail((w//2, h//2))
# print('Resize image to: %sx%s' % (w//2, h//2))
# im.save('thumbnail.jpg', 'jpeg')

# from PIL import Image, ImageFilter
# im = Image.open('./thumbnail.jpg')
# im2 = im.filter(ImageFilter.BLUR)
# im2.save('blur.jpg', 'jpeg')

# from PIL import Image, ImageDraw, ImageFont, ImageFilter
# import random

# def rndChar():
#     return chr(random.randint(65,90))

# def rndColor():
#     return (random.randint(64, 255), random.randint(64,255), random.randint(64, 255))

# def rndColor2():
#     return (random.randint(32, 127), random.randint(32, 127), random.randint(32, 127))

# width = 60*4
# height = 60
# image = Image.new('RGB', (width, height), (255,255,255))
# font = ImageFont.truetype('./simkai.ttf', 36)
# draw = ImageDraw.Draw(image)
# for x in range(width):
#     for y in range(height):
#         draw.point((x,y), fill=rndColor())
# for t in range(4):
#     draw.text((60*t + 10, 10), rndChar(), font=font, fill=rndColor2())
# image = image.filter(ImageFilter.BLUR)
# image.save('code.jpg', 'jpeg')

# 下一节
# import requests
# r = requests.get('https://www.baidu.com/', timeout=2.5)
# code = r.status_code
# print(code)
# # text = r.text
# # print(text)
# print(r.url)
# print(r.encoding)
# # print(r.content)
# print(r.headers)
# print(r.cookies)

# r = requests.get('https://')

# 下一节
# import chardet
# # result = chardet.detect(b'hjjjdd')
# # print(result)
# s = '零零零零'.encode('UTF-8')
# result = chardet.detect(s)
# print(result)

# 下一节
# import psutil
# a = psutil.cpu_count()
# a = psutil.cpu_count(logical=False)
# a = psutil.cpu_times()
# print(a)
# a = psutil.virtual_memory()
# print(a)
# a = psutil.swap_memory()
# print(a)
# a = psutil.disk_partitions()
# print(a)
# a = psutil.disk_usage('/')
# print(a)
# a = psutil.disk_io_counters()
# print(a)
# a = psutil.net_io_counters()
# print(a)
# a = psutil.net_if_addrs()
# print(a)
# a = psutil.net_if_stats()
# print(a)
# a = psutil.net_connections()
# print(a)
# a = psutil.pids()
# print(a)
# p = psutil.Process(3776)
# print(p.name())
# p = psutil.exe()
# print(p.cwd())

# 下一节
# from tkinter import *

# class Application(Frame):
#     def __init__(self, master=None):
#         Frame.__init__(self, master)
#         self.pack()
#         self.createWidgets()

#     def createWidgets(self):
#         self.helloLabel = Label(self, text='Hello, world!')
#         self.helloLabel.pack()
#         self.quitButton = Button(self, text='Quit', command=self.quit)
#         self.quitButton.pack()

# app = Application()
# app.master.title('Hello World')
# app.mainloop()

# 下一节
# from turtle import *
# width(4)
# forward(200)
# right(90)
# pencolor('red')
# forward(100)
# right(90)
# pencolor('green')
# forward(200)
# right(90)
# pencolor('blue')
# forward(100)
# right(90)
# done()

# from turtle import *
# # 设置色彩模式是RGB:
# colormode(255)

# lt(90)

# lv = 14
# l = 120
# s = 45

# width(lv)

# # 初始化RGB颜色:
# r = 0
# g = 0
# b = 0
# pencolor(r, g, b)

# penup()
# bk(l)
# pendown()
# fd(l)

# def draw_tree(l, level):
#     global r, g, b
#     # save the current pen width
#     w = width()

#     # narrow the pen width
#     width(w * 3.0 / 4.0)
#     # set color:
#     r = r + 1
#     g = g + 2
#     b = b + 3
#     pencolor(r % 200, g % 200, b % 200)

#     l = 3.0 / 4.0 * l

#     lt(s)
#     fd(l)

#     if level < lv:
#         draw_tree(l, level + 1)
#     bk(l)
#     rt(2 * s)
#     fd(l)

#     if level < lv:
#         draw_tree(l, level + 1)
#     bk(l)
#     lt(s)

#     # restore the previous pen width
#     width(w)

# speed("fastest")

# draw_tree(l, 4)

# done()

# 下一节
# import socket, threading

# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.connect(('www.baidu.com', 80))
# s.send(b'GET / HTTP/1.1\r\nHost: www.baidu.com\r\nConnection: close\r\n\r\n')
# buffer = []
# while True:
#     d = s.recv(1024)
#     if d:
#         buffer.append(d)
#     else:
#         break
# data = b''.join(buffer)
# s.close()
# header, html = data.split(b'\r\n\r\n', 1)
# print(header.decode('UTF-8'))
# with open('baidu.html', 'wb') as f:
#     f.write(html)

# 服务端Socket
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# s.bind(('127.0.0.1', 9999))
# s.listen(5)
# print('Waiting for connection...')
# while True:
#     sock, addr = s.accept()
#     t = threading.Thread(target=tcplink, args=(sock, addr))
#     t.start()

# def tcplink(sock, addr):
#     print('Accept new connection from %s:%s...' % addr)
#     sock.send(b'Welcome!')
#     while True:
#         data = sock.recv(1024)
#         time.sleep(1)
#         if not data or data.decode('UTF-8') == 'exit':
#             break
#         sock.send(('Hello, %s!' % data.decode('UTF-8')).encoding('utf-8'))
#     sock.close()
#     print('Connection from %s:%s closed.' % addr)

# 客户端Socket
# s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# # 建立连接:
# s.connect(('127.0.0.1', 9999))
# # 接收欢迎消息:
# print(s.recv(1024).decode('utf-8'))
# for data in [b'Michael', b'Tracy', b'Sarah']:
#     # 发送数据:
#     s.send(data)
#     print(s.recv(1024).decode('utf-8'))
# s.send(b'exit')
# s.close()

# 下一节
# 服务端
# import socket, threading
# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# s.bind(('127.0.0.1', 9999))
# print('Bind UDP on 9999...')
# while True:
#     print('while...')
#     data, addr = s.recvfrom(1024)
#     print('Received from %s:%s.' % addr)
#     s.sendto(b'Hello, %s!' % data, addr)
# 客户端
# s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# for data in [b'Michael', b'Tracy', b'Sarah']:
#     s.sendto(data, ('127.0.0.1', 9999))
#     print(s.recv(1024).decode('utf-8'))
# s.close()

# 下一节
# from email.mime.text import MIMEText
# msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
# from_addr = input('From:')
# password = input('Password:')
# to_addr = input('To:')
# smtp_server = input('SMTP server:')

# import smtplib
# server = smtplib.SMTP(smtp_server, 25)
# server.set_debuglevel(1)
# server.login(from_addr, password)
# server.sendmail(from_addr, [to_addr], msg.as_string())
# server.quit()

# 下一节
import sqlite3
# conn = sqlite3.connect('test.db')
# cursor = conn.cursor()
# cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# cursor.execute('insert into user (id, name) values (\'1\', \'Michael\')')
# a = cursor.rowcount
# print(a)
# cursor.close()
# conn.commit()
# conn.close()

# conn = sqlite3.connect('test.db')
# cursor = conn.cursor()
# cursor.execute('select * from user where id=?', ('1',))
# values = cursor.fetchall()
# print(values)
# cursor.close()
# conn.commit()
# conn.close()

# 练习
# import os, sqlite3

# db_file = os.path.join(os.path.dirname(__file__), 'test.db')
# if os.path.isfile(db_file):
#     os.remove(db_file)

# # 初始数据:
# conn = sqlite3.connect(db_file)
# cursor = conn.cursor()
# cursor.execute('create table user(id varchar(20) primary key, name varchar(20), score int)')
# cursor.execute(r"insert into user values ('A-001', 'Adam', 95)")
# cursor.execute(r"insert into user values ('A-002', 'Bart', 62)")
# cursor.execute(r"insert into user values ('A-003', 'Lisa', 78)")
# cursor.close()
# conn.commit()
# conn.close()

# def get_score_in(low, high):
#     ' 返回指定分数区间的名字，按分数从低到高排序 '
#     try:
#         conn = sqlite3.connect(db_file)
#         cursor = conn.cursor()
#         cursor.execute(r'select name from user where score>=? and score<=? order by score asc', (low, high))
#         values = cursor.fetchall()
#         print(values)
#     except Exception as e:
#         print(e)
#     finally:
#         cursor.close()
#         conn.close()
#     result = []
#     for v in values:
#         result.append(v[0])
#     return result

# # 测试:
# assert get_score_in(80, 95) == ['Adam'], get_score_in(80, 95)
# assert get_score_in(60, 80) == ['Bart', 'Lisa'], get_score_in(60, 80)
# assert get_score_in(60, 100) == ['Bart', 'Lisa', 'Adam'], get_score_in(60, 100)

# print('Pass')

# 下一节
# import mysql.connector
# conn = mysql.connector.connect(user='root',password='1213#MySQL',database='test')
# cursor = conn.cursor()
# cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael'])
# conn.commit()
# cursor.close()
# cursor = conn.cursor()
# cursor.execute('select * from user where id = %s', ('1',))
# values = cursor.fetchall()
# print(values)
# cursor.close()
# conn.close()

# 下一节
# from sqlalchemy import Column, String, create_engine
# from sqlalchemy.orm import sessionmaker
# from sqlalchemy.ext.declarative import declarative_base

# Base = declarative_base()

# class User(Base):
#     __tablename__ = 'user'

#     id = Column(String(20), primary_key=True)
#     name = Column(String(20))
#     books = relationship('Book')

# class School(Base):
#     __tablename__ = 'school'
#     id = Column(String(20), primary_key=True)
#     name = Column(String(20))

# class Book(Base):
#     __tablename__ = 'book'
#     id = 

# engine = create_engine('mysql+mysqlconnector://root:1213#MySQL@localhost:3306/test')
# DBSession = sessionmaker(bind=engine)
# session = DBSession()
# new_user = User(id='6', name='Jack')
# new_school = School(id='1', name='HSNF')
# session.add(new_user)
# session.add(new_school)
# user = session.query(User).filter(User.id == '5').one()
# print('type:', type(user))
# print('name:', user.name)
# session.commit()
# session.close()

# 下一节
# def application(environ, start_response):
#     start_response('200 OK', [('Content-Type', 'text/html')])
#     # return [b'<h1>Hello, Web!</h1>']
#     body = '<h1>Hello, %s!</h1>' % (environ['PATH_INFO'][1:] or 'Web')
#     return [body.encode('utf-8')]

# from wsgiref.simple_server import make_server
# # from hello import application

# httpd = make_server('', 8000, application)
# print('Serving HTTP on port 8000...')
# httpd.serve_forever()

# 下一节
# from flask import Flask
# from flask import request

# app = Flask(__name__)

# @app.route('/', methods=['GET', 'POST'])
# def home():
#     return '<h1>Home</h1>'

# @app.route('/signin', methods=['GET'])
# def signin_form():
#     return '''<form action="/signin" method="post">
#               <p><input name="username"></p>
#               <p><input name="password" type="password"></p>
#               <p><button type="submit">Sign In</button></p>
#               </form>'''

# @app.route('/signin', methods=['POST'])
# def signin():
#     if request.form['username']=='admin' and request.form['password']=='password':
#         return '<h3>Hello, admin!</h3>'
#     return '<h3>Bad username or password</h3>'    

# if __name__ == '__main__':
#     app.run()

# 下一节
# import os
# print(os.path.abspath('.'))
# print(__file__)

import sys
print(sys.argv)
print(sys.executable)
